package com.ds.log.remote;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.trace.http.HttpTrace;
import org.springframework.boot.actuate.trace.http.HttpTraceRepository;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

@Slf4j
@Component
public class RemoteHttpTraceRepository implements HttpTraceRepository {
    private final List<HttpTrace> traces = new LinkedList<>();


    @Override
    public List<HttpTrace> findAll() {
        synchronized (this.traces) {
            return Collections.unmodifiableList(new ArrayList<>(this.traces));
        }
    }

    @Override
    @Async
    public void add(HttpTrace trace) {

        String path = trace.getRequest().getUri().getPath();
        String queryPara = trace.getRequest().getUri().getQuery();
        String queryParaRaw = trace.getRequest().getUri().getRawQuery();
        String method = trace.getRequest().getMethod();
        long timeTaken = trace.getTimeTaken();
//        String time = trace.getTimestamp().plusMillis(TimeUnit.HOURS.toMillis(8)).toString();
        LocalDateTime time = trace.getTimestamp().atZone(ZoneId.systemDefault()).toLocalDateTime();
        System.out.println(path);
        System.out.println( queryPara);
        System.out.println( queryParaRaw);
        System.out.println( timeTaken);
        System.out.println( time);
        System.out.println( method);
//        System.out.println(RegexTest.UTCToCST(trace.getTimestamp().toString(),"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));

        log.info("path: {}, queryPara: {}, queryParaRaw: {}, timeTaken: {}, time: {}, method: {}", path, queryPara, queryParaRaw,
                timeTaken, time, method);
    }
}